<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="list-box">
    <DetailTabs v-model="paramsObj.platform" :tabs="tabData" @tabClick="switchTab" />
    <div class="operate">
      <div class="input-box">
        <el-input v-model="paramsObj.account" placeholder="请输入账号" class="input-with-select" size="small">
          <el-button slot="append" icon="el-icon-search" @click="queryClick"/>
        </el-input>
      </div>
      <el-checkbox v-model="paramsObj.onlyValidLink" :true-label="1" :false-label="0" @change="queryClick">只看有效链接</el-checkbox>
      <div class="text">数据更新时间：{{ format(list.updateTime,'YYYY/MM/DD HH:mm:ss') }}</div>
    </div>
    <DataDisplay :data-list="dataList" class="data-display" />
    <div class="table-list">
      <div v-loading="listLoading" style="min-height: 100px" class="table-box">
        <u-table
          v-if="list.items.length"
          ref="publishList"
          :data="list.items"
          :border="true"
          :row-height="rowHeight(56)"
          :row-class-name="(data) => tableRowClassName(data)"
          beautify-table
          header-drag-style
          row-key="id"
          use-virtual
          element-loading-text="加载中..."
          empty-text="暂无数据"
          fit
          class="fb-table"
          header-cell-class-name="order-data-header-cell"
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod"
        >
          <u-table-column
            align="center"
            type="selection"
            width="50"
            fixed="left"/>
          <u-table-column :fixed="selectFixed" align="left" label="账号名称" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.account" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单平台" min-width="120">
            <template slot-scope="scope">
              <div :class="{ 'gray-filter': scope.row.status === 0 }" class="flex-center">
                <platformIcon :data="scope.row.platformTypeName" />
                {{ scope.row.platformTypeName || '--' }}
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="品牌名称" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.brandName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布链接" min-width="120">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.publishUrl && (scope.row.publishUrl.indexOf('http://') === 0 || scope.row.publishUrl.indexOf('https://') === 0)"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.publishUrl }}</div>
                <a
                  :href="scope.row.publishUrl"
                  target="_blank"
                  class="link-name light-word">
                  点击跳转
                </a>
              </el-tooltip>
              <ToolTip v-else :content="scope.row.publishUrl" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布文案" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.publishRemark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布数据" min-width="355">
            <template slot-scope="scope">
              <div v-if="showPublishData(scope.row.platformTypeName)" class="publish-data">
                <img v-if="showPublishIcon(scope.row)" :src="defaultIcon" class="pointer" alt="icon" @click="openChart(scope.row)">
                <span
                  v-for="(item, index) in getPublishDataIcon(scope.row.platformTypeName)"
                  :key="index"
                  :class="{'last-item': index === 2}"
                  :style="{ marginLeft: scope.row.publishUrl ? '0' : '20px'}"
                  class="publish-data-item">
                  {{ item.tip }} : {{ scope.row.publishData[item.key] | bigDataFilter }}
                </span>
              </div>
              <div v-else class="ml20" >暂不采集</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布日期" width="150" prop="publishTime" sortable="custom">
            <template slot-scope="scope">
              <div>{{ format(scope.row.publishTime, 'YYYY/MM/DD HH:mm') }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布截图" min-width="150">
            <template slot-scope="scope">
              <FileShowList
                :file-list="scope.row.attachment"
                :table-single="true"
                :show-image="false"
                is-show-single-file
              />
            </template>
          </u-table-column>
          <u-table-column align="left" label="采集状态" min-width="110">
            <template slot-scope="scope">
              <div style="display:flex;align-items:center;">
                <span :style="{backgroundColor: getPickStatusColor(scope.row.pickStatus)}" class="dot"/>
                {{ scope.row.pickStatus | getPickStatus }}
              </div>
            </template>
          </u-table-column>
          <!-- <u-table-column align="left" label="运营人员">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.accountOperationName" />
            </template>
          </u-table-column> -->
          <!-- <u-table-column align="left" label="所属经营体" width="120">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.resourceAttributionMatrix"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px">{{ scope.row.entityTip }}</div>
                <div class="resource-name ellipsisOne" style="max-width: 120px">{{ scope.row.resourceAttributionMatrix }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column> -->
          <u-table-column align="left" label="创建时间" width="150" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.createTime, 'YYYY/MM/DD HH:mm')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.creator" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="主页链接" min-width="120">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.homeLink && (scope.row.homeLink.indexOf('http://') === 0 || scope.row.homeLink.indexOf('https://') === 0)"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.homeLink }}</div>
                <a
                  :href="scope.row.homeLink"
                  target="_blank"
                  class="link-name light-word">
                  点击跳转
                </a>
              </el-tooltip>
              <ToolTip v-else :content="scope.row.homeLink" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="账号ID" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.accountId" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="粉丝量" min-width="150" prop="fans" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.fans" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="数据更新时间" min-width="150" prop="updateTime" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.updateTime, 'YYYY/MM/DD HH:mm')" />
            </template>
          </u-table-column>
          <u-table-column :min-width="showMobilePage ? 50 : (paramsObj.platform !== -1?140:80)" align="left" label="操作" fixed="right">
            <template slot-scope="scope">
              <template v-if="!showMobilePage">
                <el-button v-if="paramsObj.platform !== -1" :disabled="!hasRouteAuth('publish:publishList:addPick') || scope.row.pickStatus === 2" type="text" @click="reCollect(scope.row.id)"><span style="font-size:14px;">重新采集</span></el-button>
                <el-button type="text" @click="toDelete(scope.row.id)"><span style="font-size:14px;">删除</span></el-button>
              </template>
              <tableOperateBtn v-else>
                <el-dropdown-item v-if="paramsObj.platform !== -1" :disabled="!hasRouteAuth('publish:publishList:addPick') || scope.row.pickStatus === 2" @click.native="reCollect(scope.row.id)">
                  <div style="font-size: 14px">重新采集</div>
                </el-dropdown-item>
                <el-dropdown-item @click.native="toDelete(scope.row.id)">
                  <div style="font-size: 14px">删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <EmptyPlaceholder v-else :empty-img-top="'40px'" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <el-row type="flex" justify="center" class="row-box">
        <MoreOpeator
          v-if="list.items.length"
          ref="moreOpeatorRef"
          :list="[
            { status: 1, label: '加入采集', auth: hasRouteAuth('publish:publishList:addPick')},
            { status: 4, label: '删除', auth: hasRouteAuth('publish:publishList:delete')}
          ]"
          :handel-click="pickOperate"
          style="margin-right:10px;"
        />
        <div v-if="!showMobilePage" class="delete-button-container" style="flex: 1">
          <div style="flex:1;" class="flex-center">
            <div v-if="selectData.length" class="select-box-style">
              <span class="select-data-num">已选 <span>{{ selectData.length }}</span> 条</span>
              <el-button type="text" @click="clearSelect"><span class="el-icon-close"/></el-button>
            </div>
          </div>
        </div>
        <el-pagination
          v-if="!showMobilePage"
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[10, 20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <PublishChart ref="publishChartRef" :publish-url="publishUrl" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import FileShowList from '@/components/CreateOrder/fileShowList';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { getPublishDetailList, deleteLink, putPublishStatus } from '@/api/publish';
import { getPickStatus, getPickStatusColor } from '@/filters/status';
import { bigDataFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import ElMessage from '@/utils/message';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import defaultIcon from '@/assets/lookData.png';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import PublishChart from '@/components/CreateOrder/orderDetail/publishChart';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import icon_47 from '@/assets/dataDisplay/icon_47.png';
import icon_48 from '@/assets/dataDisplay/icon_48.png';
import icon_49 from '@/assets/dataDisplay/icon_49.png';
import icon_50 from '@/assets/dataDisplay/icon_50.png';

export default {
  filters: {
    getPickStatus,
    bigDataFilter
  },
  components: {
    EmptyPlaceholder,
    FileShowList,
    platformIcon,
    DataDisplay,
    DetailTabs,
    PublishChart,
    MoreOpeator
  },
  mixins: [TableAdaptive, mobileTable],
  props: {
    id: {
      type: Number | String,
      default: null
    }
  },
  data() {
    return {
      defaultIcon,
      list: {
        items: [],
        total: 0
      },
      page: 1,
      perPage: 10,
      sortType: '',
      sortName: '',
      paramsObj: {
        platform: 1
      },
      listLoading: false,
      cancelToken: null,
      ids: '',
      selectData: [],
      publishUrl: '',
      dataList: [
        { label: '链接数量', data: 0, icon: icon_49 },
        { label: '有效链接', data: 0, icon: icon_47 },
        { label: '采集中', data: 0, icon: icon_50 },
        { label: '问题链接', data: 0, icon: icon_48 }
      ],
      tabData: [
        { name: '微信', id: 1 },
        { name: '微博', id: 2 },
        { name: '小红书', id: 3 },
        { name: '抖音', id: 4 },
        { name: '其他', id: -1 }
      ]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [{ keyword: 'account', name: '账号', type: 'input', labelWidth: '70px' }];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 200 : 0;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.clearSelectData();
    this.fetchData();
  },
  methods: {
    hasRouteAuth,
    format,
    getPickStatusColor,
    switchTab() {
      this.fetchData(true);
    },
    showPublishData(p) {
      return ['微信', '小红书', '微博', '抖音'].includes(p);
    },
    showPublishIcon(row) {
      return row.publishUrl && (row.orderId || row.id);
    },
    getPublishDataIcon(platform) {
      return {
        '微信': [
          { key: 'read', icon: 'read', tip: '阅读' },
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'look', icon: 'look', tip: '在看' }
        ],
        '小红书': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'collect', icon: 'collect', tip: '收藏' }
        ],
        '微博': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'share', icon: 'share', tip: '转发' }
        ],
        '抖音': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'share', icon: 'share', tip: '转发' }
        ]
      }[platform];
    },
    toOrderDetail(row) {
      if (!hasRouteAuth('publish:publishList:goToOrder')) {
        return;
      }
      let url;
      if (row.category === 1) {
        url = this.$router.resolve({
          name: 'projectChildDetail',
          params: { id: row.orderId }
        });
      } else if (row.category === 0) {
        url = this.$router.resolve({
          name: 'orderDetail',
          params: { orderId: row.orderId }
        });
      }
      url && window.open(url.href, '_blank');
    },
    // 选择表格
    selectTable(e) {
      this.selectData = e.map(item => { return item.id; });
      this.ids = this.selectData.join(',');
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    clearSelect() {
      showModal('是否清空已勾选的数据？', '').then(() => {
        this.clearSelectData();
        this.$refs.publishList.clearSelection();
      });
    },
    clearSelectData() {
      this.selectData = [];
      this.ids = '';
      if (this.$refs.publishList && this.$refs.publishList.clearSelection) {
        this.$refs.publishList.clearSelection();
      }
    },
    clearMixinSelection() {
      this.selectData = [];
      this.ids = '';
      if (this.$refs.publishList && this.$refs.publishList.clearMixinSelection) {
        this.$refs.publishList.clearMixinSelection();
      }
    },
    handleTabClick(id) {
      this.list = { items: [] };
      this.clearSelectData();
      this.fetchData(true);
    },
    async reCollect(id) {
      const params = {
        status: 1,
        ids: id ? [id] : this.selectData
      };
      try {
        const res = await putPublishStatus(params);
        if (res.code === 200) {
          this.fetchData();
          this.clearSelectData();
          ElMessage.success(res.message);
        } else {
          ElMessage.error(res.message);
        }
      } catch (err) {
        this.confirm(err.message, params);
      }
    },
    toDelete(id) {
      showModal('是否删除当前选择的内容？', '').then(() => {
        const params = { ids: id ? `${id}` : this.selectData.join(',') };
        deleteLink(params).then(res => {
          if (res.code === 200) {
            // 当前页是否只有一条数据，是则页数-1
            if (this.list.items.length === 1 && this.page > 1) {
              this.page -= 1;
            }
            this.fetchData();
            this.clearSelectData();
            ElMessage.success(res.message);
            if (res.data.isAllDelete) {
              this.handleBack();
            }
          } else {
            ElMessage.error(res.message);
          }
        }).catch(err => {
          console.log(err);
        });
      });
    },
    async pickOperate(i) {
      if (this.selectData.length === 0) {
        ElMessage.warning('请选择发布信息');
        return;
      }
      if (i.status === 4) {
        this.toDelete();
      } else {
        this.reCollect();
      }
    },
    handleBack() {
      this.$router.push({
        name: 'publish'
      });
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (this.sortType || this.sortName) {
        params.sortName = this.sortName;
        params.sortType = this.sortType;
      }
      return params;
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      let params = this.getParams();
      params = {
        ...params,
        page: this.page,
        perPage: this.perPage,
        id: this.id
      };
      getPublishDetailList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        const { statistics } = res.data;
        this.dataList = [
          { label: '链接数量', data: statistics.importLink, icon: icon_49 },
          { label: '有效链接', data: statistics.validLink, icon: icon_47 },
          { label: '采集中', data: statistics.collecting, icon: icon_48 },
          { label: '问题链接', data: statistics.problemLink, icon: icon_50 }
        ];
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    openChart(row) {
      this.publishUrl = row.publishUrl;
      this.$refs.publishChartRef.activeName = 7;
      const id = row.orderId || row.id;
      this.$refs.publishChartRef.openDialog(id, row.publishUrl);
    },
    tableRowClassName({ row, rowIndex }) {
      if (this.selectData && this.selectData.length > 0) {
        const ids = this.selectData;
        return ids.includes(row['id']) ? `table-selected` : '';
      }
      return '';
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FFBC3D 0, #FD8546 1, #FF4E5F 2, #999 3, #31CC9C 4, #406EFF 5;
.list-box {
  background-color: #fff;
  min-height: calc(100vh - 350px);
}
.operate {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  margin: 16px 0 12px;
  .input-box {
    width: 240px !important;
    margin-right: 12px;
    &::v-deep {
      .el-input-group__append {
        background-color: #406EFF;
        border: 0;
      }
    }
  }
  .text {
    margin-left: 16px;
    font-size: 14px;
    color: #999;
  }
}
.data-display {
  margin-bottom: 12px;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
  @each $c, $i in $bgc {
    &.color-#{$i} {
      background: $c;
    }
  }
}
.table-box {
  margin-bottom: 10px;
}
.row-box {
  ::v-deep {
    .el-pagination {
      padding-top: 0 !important;
      padding-bottom: 0 !important;
    }
  }
}
.pointer {
  cursor: pointer;
}
.delete-button-container {
  flex:1;
  height: 32px;
  display: flex;
  align-items: center;
}
.light-word{
  color: #406eff;
}
.link-name{
  display: flex;
  align-items: center;
  img{
    width: 14px;
    height: 15px;
    margin-left: 4px;
  }
}
.publish-data{
  display: flex;
  align-items: center;
  img{
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
  .img-container {
    display: flex;
  }
  .ml20 {
    margin-left: 20px;
  }
}
.publish-data-item{
  display: inline-block;
  width: 108px;
  &.last-item{
    width: 93px;
  }
}
.select-box-style{
  height: 30px;
  line-height: 30px;
  display: flex;
  align-items: center;
  background-color: #fafafc;
  padding: 5px 12px;
  text-align: center;
  font-size: 14px;
  color: #666;
  .select-data-num{
    display: inline-block;
    margin-right: 5px;
    span{
      // margin: 0 5px;
      color: #406eff;
      font-size: 14px;
      font-weight: 600;
    }
  }
}
</style>
